//
//  AlbumsViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/6.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let reuseIdentifier = "ReaderCell"

class ReadersViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet private weak var collectionView: UICollectionView!
  
  
  // MARK: - Private vars
  
  private var isFirstLoaded = true
  private var readersArray: [Reader]?
  
  // MARK: - Private methods
  
  private func loadData() {
    API.shared.requestAPI(APIURLStrings.readers, method: .get, successCallback: { json in
      
      if let readersJSON = json["readers"].arrayObject as? [[String: Any]] {
        EntityManager.sync (
          type: Reader.self,
          rawObject: readersJSON,
          operations: [.insert, .update], completion: { error, readers in
            if error == nil {
              self.readersArray = readers!
              self.collectionView.reloadData()
            }
        })
      }
      
      UIView.animate(withDuration: 0.3) {
        self.collectionView.alpha = 1
      }
      
    }) { (message, code) in
      loggingPrint("[\(code)]: \(message)")
    }
  }
  
  private func displayLoginView() {
    let alert = UIAlertController (
      title: "尚未登录",
      message: "请登录后再查看主播节目",
      cancelTitle: "取消",
      cancelHandler: nil,
      confirmTitle: "登录") { _ in
        let loginViewController = UIStoryboard(name: "Account", bundle: nil).instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
        loginViewController.addCloseButton()
        let nav = BaseNavigationController(rootViewController: loginViewController, dismissDelegate: self)
        nav.isPresentedModally = true
        self.present(nav, animated: true)
    }
    present(alert, animated: true)
  }
  
  // MARK: - Public vars
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // Do any additional setup after loading the view.
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    if isFirstLoaded {
      collectionView!.alpha = 0
    }
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    
    if isFirstLoaded {
      loadData()
      isFirstLoaded = false
    }
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "ShowReaderAlbumsSegue" {
      let personAlbumsViewController = segue.destination as! PersonAlbumsViewController
      if let cell = sender as? ReaderCell,
        let indexPath = collectionView.indexPath(for: cell),
        let reader = readersArray?[indexPath.row] {
        personAlbumsViewController.simplePerson = SimplePerson (
          type: .reader,
          name: reader.name!,
          identifier: Int(reader.id)
        )
      }
    }
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  
  
  // MARK: - Public methods
  
  
}

// MARK: - UICollectionViewDataSource

extension ReadersViewController: UICollectionViewDataSource {
  
  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
  }
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return readersArray?.count ?? 0
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ReaderCell
    
    if let reader = readersArray?[indexPath.row] {
      cell.prepare(reader: reader)
    }
    return cell
  }
}

// MARK: - UICollectionViewDelegate

extension ReadersViewController: UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if UserManager.shared.currentUser != nil {
      let cell = collectionView.cellForItem(at: indexPath)
      performSegue(withIdentifier: "ShowReaderAlbumsSegue", sender: cell)
    } else {
      displayLoginView()
    }
  }
}

extension ReadersViewController: UICollectionViewDelegateFlowLayout {
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: (collectionView.width - 32) / 3 - 16, height: PersonView.defaultHeight)
  }
}

// MARK: - BaseNavigationControllerDismissDelegate

extension ReadersViewController: BaseNavigationControllerDismissDelegate {
  func dismiss(navigationController: BaseNavigationController, completion: (() -> Void)?) {
    dismiss(animated: true, completion: completion)
  }
}
